﻿using FlickrNet;
using Lsk.Business;
using Lsk.Business.DTO;
using Lsk.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace lsk.Web.Api
{
    public class PropertyController : ApiController
    {
        [HttpGet]
        public IEnumerable<GetSalePropertyByAgent_Result> Agent(string id)
        {

            PropertySearch srchMgr = new PropertySearch();
            IEnumerable<GetSalePropertyByAgent_Result> results = srchMgr.GetSalePropertiesByAgent(id);
            return results;
        }
        [HttpGet]
        public IEnumerable<GetRentPropertyByAgent_Result> Agent_Rent(string id)
        {

            PropertySearch srchMgr = new PropertySearch();
            IEnumerable<GetRentPropertyByAgent_Result> results = srchMgr.GetRentPropertiesByAgent(id);
            return results;
        }

        [HttpGet]
        public IEnumerable<GetState_Result> GetState()
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetState();

        }

        [HttpGet]
        public IEnumerable<GetLocationByStateId_Result> GetLocation(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetLocation(id);
        }

        [HttpGet]
        public IEnumerable<GetRoadName_Result> GetRoadName(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetRoadName(id);
        }

        [HttpGet]
        public IEnumerable<GetProject_Result> GetProject(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetProject(id);
        }

        [HttpGet]
        public IEnumerable<AW_PropertyType> GetPropertyType()
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetPropertyType();
        }

        [HttpPost]
        public HttpResponseMessage DeletePhoto(dynamic photoId)
        {
            long PhotoId = photoId;
            Property propertyMgr = new Property();
            propertyMgr.DeletePictureByPhotoId(PhotoId.ToString());
            return Request.CreateResponse(HttpStatusCode.OK, "Deleted");
        }


        [HttpPost]
        [Authorize]
        public HttpResponseMessage save(dynamic data)
        {
            //ListingEntry entry = JsonConvert.DeserializeObject<ListingEntry>(data.ToString());
            AW_Property entry = JsonConvert.DeserializeObject<AW_Property>(data.ToString());

            Property propertyMgr = new Property();
            ResponseMessage msg =propertyMgr.SaveListing(entry);
            return Request.CreateResponse(HttpStatusCode.OK, msg);

        }


        public ResponseMessage GetProperty(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetProperty(id);

        }

        public ResponseMessage GetPropertyDetail(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetPropertyDetailById(id);

        }
        [HttpGet]
        public ResponseMessage GetPropertyDetailByListType(string id, string listType)
        {
            
            Property propertyMgr = new Property();
            return propertyMgr.GetPropertyDetailByListType(id, listType);

        }


        [HttpPost]
	        public ResponseMessage GetPropertyByLatLng(dynamic data)
	        {
	            LatLngParameter entry = JsonConvert.DeserializeObject<LatLngParameter>(data.ToString());
	 
	            Property propertyMgr = new Property();
	            return propertyMgr.GetPropertyDetailByLatLng(entry.lng, entry.lat, entry.distant, entry.listType);
	        }

        [HttpPost]
	        public IEnumerable<GetNearByProperty_Result> GetPropertyByLatLngType(dynamic data)
	        {
	            LatLngParameter entry = JsonConvert.DeserializeObject<LatLngParameter>(data.ToString());
	 
	            Property propertyMgr = new Property();
	            return propertyMgr.GetPropertiesByTypeLatLng(entry.lng, entry.lat, entry.distant, entry.listType);
	        }


    public PhotoInfo base64ToImage(string data,AW_Property entry)
        {
            PhotoManager photMgr = new PhotoManager();
            AW_Picture picture = new AW_Picture();
            picture.PictureId = Guid.NewGuid();
            picture.PictureDesc =  entry.PropertyId.ToString();
            picture.Picture = entry.PropertyTypeId.ToString();
            picture.CreateDate = DateTime.Now;
            picture.PropertyId = entry.PropertyId;
            picture.isThumbnail = 2;
            try {
                string base64Data = Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
                var binData = Convert.FromBase64String(base64Data);
                using (var stream = new MemoryStream(binData))
                {
                    try {
                        PhotoInfo info = photMgr.Upload(stream, picture);
                        picture.PhotoId = info.PhotoId;
                        picture.MediumUrl = info.MediumUrl;
                        picture.pictureURL = info.OriginalUrl;
                        picture.SmallUrl = info.SmallUrl;
                        picture.LargeUrl = info.LargeUrl;
                        photMgr.Save(picture);
                        return info;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Flickr failed!" + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Convert base64 failedd!" + ex.Message);
            }
           
         
                
        }

        [HttpPost]
        [Authorize]
        public async Task<HttpResponseMessage> upload() 
        {
            var root = HttpContext.Current.Server.MapPath("~/");
            var provider = new MultipartFormDataStreamProvider(root);
            String programTrack = "";
            try 
            {
                PhotoInfo photo = new PhotoInfo();
                // Read the form data.
                programTrack = "ReadAsMultipartAsync";
                await Request.Content.ReadAsMultipartAsync(provider);

                // Show all the key-value pairs.
                programTrack = programTrack + "-->DeserializeObject";
                AW_Property entry = JsonConvert.DeserializeObject<AW_Property>(provider.FormData.GetValues("property")[0]);

                programTrack = programTrack + "-->base64ToImage";
                photo =base64ToImage(provider.FormData.GetValues("image")[0], entry);

                //foreach(var key in provider.FormData.AllKeys) 
                //{
                //    foreach(var val in provider.FormData.GetValues(key)) 
                //    {                                      
                //        photo = base64ToImage(val);
                //    }
                //}

                //foreach(MultipartFileData fileData in provider.FileData) 
                //{
                //    var fileName = fileData.Headers.ContentDisposition.FileName;
                //}

                //  var httpRequest = HttpContext.Current.Request;
                // if (httpRequest.Files.Count > 0)
                //{
                //    var docfiles = new List<string>();
                //  foreach (string file in httpRequest.Files)
                //    {
                //        var postedFile = httpRequest.Files[file];
                //        var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                //        postedFile.SaveAs("C:\\Test\\" + postedFile.FileName);
 
                //        docfiles.Add(filePath);
                //    }
                // }

                // output photo object
                programTrack = programTrack + "-->CreateResponse";
                 return Request.CreateResponse(HttpStatusCode.OK, photo);
                
            } 

               
            catch (Exception ex) 
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,"Error Upload Photo!" + programTrack + ex.Message); // + "  \n" + e.InnerException.Message.ToString() +" \n" + e.InnerException.StackTrace.ToString());
            }
        }


    }
}
